home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 May: Tool Chest / Developer CD Series May 1996 (Tool Chest) (Apple Computer) (1996).iso / Sample Code / Snippets / Toolbox / WDEFColorSample / WDEFColorSample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-12-09  |  27.0 KB  |  829 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    System 7 WDEF Colorization sample
  6. #
  7. #    WDEFColorSample
  8. #
  9. #    WDEFColorSample.c    -    C Source
  10. #
  11. #    Copyright © Apple Computer, Inc. 1989-1992
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                05/92
  16. #
  17. #    Components:
  18. #                WDEFColorSample.c            05/92
  19. #                WDEFColorSample.r            05/92
  20. #                WDEFColorSample.h            05/92
  21. #                WDEFColorSampleWDEF.c        05/92
  22. #
  23. #    WDEFSample shows in high level what the system 7 WDEF does as far as
  24. #    choosing colors is concerned.
  25. #    
  26. #    Based in Sample it does not have the complete comments as its originator
  27. #    does, please check MPW Sample for overall comments.
  28. ------------------------------------------------------------------------------*/
  29.  
  30.  
  31.     #include <Values.h>
  32.     #include <Types.h>
  33.     #include <Resources.h>
  34.     #include <QuickDraw.h>
  35.     #include <Fonts.h>
  36.     #include <Events.h>
  37.     #include <Windows.h>
  38.     #include <Menus.h>
  39.     #include <TextEdit.h>
  40.     #include <Dialogs.h>
  41.     #include <Desk.h>
  42.     #include <ToolUtils.h>
  43.     #include <Memory.h>
  44.     #include <SegLoad.h>
  45.     #include <Files.h>
  46.     #include <OSUtils.h>
  47.     #include <OSEvents.h>
  48.     #include <DiskInit.h>
  49.     #include <Packages.h>
  50.     #include <Traps.h>
  51.  
  52.  
  53. #include "WDEFColorSample.h"        /* bring in all the #defines for WDEFColorSample */
  54.  
  55.  
  56. /* The "g" prefix is used to emphasize that a variable is global. */
  57.  
  58. /* GMac is used to hold the result of a SysEnvirons call. This makes
  59.    it convenient for any routine to check the environment. */
  60. SysEnvRec    gMac;                /* set up by Initialize */
  61.  
  62. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  63.    trap is available. If it is false, we know that we must call GetNextEvent. */
  64. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  65.  
  66. /* GInBackground is maintained by our osEvent handling routines. Any part of
  67.    the program can check it to find out if it is currently in the background. */
  68. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  69.  
  70.  
  71. /* The following globals are the state of the window. If we supported more than
  72.    one window, they would be attatched to each document, rather than globals. */
  73.  
  74. /* GStopped tells whether the stop light is currently on stop or go. */
  75. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  76.  
  77. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  78. Rect        gStopRect;            /* set up by Initialize */
  79. Rect        gGoRect;            /* set up by Initialize */
  80.  
  81.  
  82. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  83.    actual prototypes for parameter type checking. */
  84. void EventLoop( void );
  85. void DoEvent( EventRecord *event );
  86. void AdjustCursor( Point mouse, RgnHandle region );
  87. void GetGlobalMouse( Point *mouse );
  88. void DoUpdate( WindowPtr window );
  89. void DoActivate( WindowPtr window, Boolean becomingActive );
  90. void DoContentClick( WindowPtr window );
  91. void DrawWindow( WindowPtr window );
  92. void AdjustMenus( void );
  93. void DoMenuCommand( long menuResult );
  94. void SetLight( WindowPtr window, Boolean newStopped );
  95. Boolean DoCloseWindow( WindowPtr window );
  96. void Terminate( void );
  97. void Initialize( void );
  98. Boolean GoGetRect( short rectID, Rect *theRect );
  99. void ForceEnvirons( void );
  100. Boolean IsAppWindow( WindowPtr window );
  101. Boolean IsDAWindow( WindowPtr window );
  102. Boolean TrapAvail( short tNumber, TrapType tType );
  103. void AlertUser( void );
  104.  
  105. extern void FakeWDEF(WindowPtr window, Boolean hilite);
  106.  
  107. /* Define HiWrd and LoWrd macros for efficiency. */
  108. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  109. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  110.  
  111. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  112.    dependency on the ordering of fields within a Rect */
  113. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  114. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  115.  
  116.  
  117. extern void _DataInit();
  118.  
  119. /* This routine is part of the MPW runtime library. This external
  120.    reference to it is done so that we can unload its segment, %A5Init. */
  121.  
  122.  
  123. #pragma segment Main
  124. main()
  125. {
  126.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  127.     
  128.     /* 1.01 - call to ForceEnvirons removed */
  129.     
  130.     /*    If you have stack requirements that differ from the default,
  131.         then you could use SetApplLimit to increase StackSpace at 
  132.         this point, before calling MaxApplZone. */
  133.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  134.  
  135.     Initialize();                    /* initialize the program */
  136.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  137.  
  138.     EventLoop();                    /* call the main event loop */
  139. }
  140.  
  141.  
  142. /*    Get events forever, and handle them by calling DoEvent.
  143.     Get the events by calling WaitNextEvent, if it's available, otherwise
  144.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  145.  
  146. #pragma segment Main
  147. void EventLoop()
  148. {
  149.     RgnHandle    cursorRgn;
  150.     Boolean        gotEvent;
  151.     EventRecord    event;
  152.     Point        mouse;
  153.  
  154.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  155.     do {
  156.         /* use WNE if it is available */
  157.         if ( gHasWaitNextEvent ) {
  158.             GetGlobalMouse(&mouse);
  159.             AdjustCursor(mouse, cursorRgn);
  160.             gotEvent = WaitNextEvent(everyEvent, &event, 60, cursorRgn);
  161.         }
  162.         else {
  163.             SystemTask();
  164.             gotEvent = GetNextEvent(everyEvent, &event);
  165.         }
  166.         if ( gotEvent ) {
  167.             /* make sure we have the right cursor before handling the event */
  168.             AdjustCursor(event.where, cursorRgn);
  169.             DoEvent(&event);
  170.         }
  171.         /*    If you are using modeless dialogs that have editText items,
  172.             you will want to call IsDialogEvent to give the caret a chance
  173.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  174.             for a non-NIL value before calling IsDialogEvent. */
  175.     } while ( true );    /* loop forever; we quit via ExitToShell */
  176. } /*EventLoop*/
  177.  
  178.  
  179. /* Do the right thing for an event. Determine what kind of event it is, and call
  180.  the appropriate routines. */
  181.  
  182. #pragma segment Main
  183. void DoEvent(event)
  184.     EventRecord    *event;
  185. {
  186.     short        part, err;
  187.     WindowPtr    window;
  188.     Boolean        hit;
  189.     char        key;
  190.     Point        aPoint;
  191.  
  192.     switch ( event->what ) {
  193.         case mouseDown:
  194.             part = FindWindow(event->where, &window);
  195.             switch ( part ) {
  196.                 case inMenuBar:                /* process a mouse menu command (if any) */
  197.                     AdjustMenus();
  198.                     DoMenuCommand(MenuSelect(event->where));
  199.                     break;
  200.                 case inSysWindow:            /* let the system handle the mouseDown */
  201.                     SystemClick(event, window);
  202.                     break;
  203.                 case inContent:
  204.                     if ( window != FrontWindow() ) {
  205.                         SelectWindow(window);
  206.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  207.                     } else
  208.                         DoContentClick(window);
  209.                     break;
  210.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  211.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  212.                     break;
  213.                 case inGrow:
  214.                     break;
  215.                 case inZoomIn:
  216.                 case inZoomOut:
  217.                     hit = TrackBox(window, event->where, part);
  218.                     if ( hit ) {
  219.                         SetPort(window);                /* the window must be the current port... */
  220.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  221.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  222.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  223.                     }
  224.                     break;
  225.             }
  226.             break;
  227.         case keyDown:
  228.         case autoKey:                        /* check for menukey equivalents */
  229.             key = event->message & charCodeMask;
  230.             if ( event->modifiers & cmdKey )            /* Command key down */
  231.                 if ( event->what == keyDown ) {
  232.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  233.                     DoMenuCommand(MenuKey(key));
  234.                 }
  235.             break;
  236.         case activateEvt:
  237.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  238.             break;
  239.         case updateEvt:
  240.             DoUpdate((WindowPtr) event->message);
  241.             break;
  242.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  243.             to a diskEvt, so that the user can format a floppy. */
  244.         case diskEvt:
  245.             if ( HiWord(event->message) != noErr ) {
  246.                 SetPt(&aPoint, kDILeft, kDITop);
  247.                 err = DIBadMount(aPoint, event->message);
  248.             }
  249.             break;
  250.         case kOSEvent:
  251.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  252.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  253.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  254.                     gInBackground = (event->message & kResumeMask) == 0;
  255.                     DoActivate(FrontWindow(), !gInBackground);
  256.                     break;
  257.             }
  258.             break;
  259.     }
  260. } /*DoEvent*/
  261.  
  262.  
  263. /*    Change the cursor's shape, depending on its position. This also calculates the region
  264.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  265.     that region, an event would be generated, causing this routine to be called,
  266.     allowing us to change the region to the region the mouse is currently in. If
  267.     there is more to the event than just “the mouse moved”, we get called before the
  268.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  269.     this is called again before we     fall back into WNE. */
  270.  
  271. #pragma segment Main
  272. void AdjustCursor(mouse,region)
  273.     Point        mouse;
  274.     RgnHandle    region;
  275. {
  276.     WindowPtr    window;
  277.     RgnHandle    arrowRgn;
  278.     RgnHandle    plusRgn;
  279.     Rect        globalPortRect;
  280.  
  281.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  282.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  283.         /* calculate regions for different cursor shapes */
  284.         arrowRgn = NewRgn();
  285.         plusRgn = NewRgn();
  286.  
  287.         /* start with a big, big rectangular region */
  288.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  289.  
  290.         /* calculate plusRgn */
  291.         if ( IsAppWindow(window) ) {
  292.             SetPort(window);    /* make a global version of the viewRect */
  293.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  294.             globalPortRect = window->portRect;
  295.             RectRgn(plusRgn, &globalPortRect);
  296.             SectRgn(plusRgn, window->visRgn, plusRgn);
  297.             SetOrigin(0, 0);
  298.         }
  299.  
  300.         /* subtract other regions from arrowRgn */
  301.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  302.  
  303.         /* change the cursor and the region parameter */
  304.         if ( PtInRgn(mouse, plusRgn) ) {
  305.             SetCursor(*GetCursor(plusCursor));
  306.             CopyRgn(plusRgn, region);
  307.         } else {
  308.             SetCursor(&qd.arrow);
  309.             CopyRgn(arrowRgn, region);
  310.         }
  311.  
  312.         /* get rid of our local regions */
  313.         DisposeRgn(arrowRgn);
  314.         DisposeRgn(plusRgn);
  315.     }
  316. } /*AdjustCursor*/
  317.  
  318.  
  319. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  320.     it will return either a pending event or a null event. In either case,
  321.     the where field of the event record will contain the current position
  322.     of the mouse in global coordinates and the modifiers field will reflect
  323.     the current state of the modifiers. Another way to get the global
  324.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  325.     being sure that thePort is set to a valid port. */
  326.  
  327. #pragma segment Main
  328. void GetGlobalMouse(mouse)
  329.     Point    *mouse;
  330. {
  331.     EventRecord    event;
  332.     
  333.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  334.     *mouse = event.where;                /* just the mouse position */
  335. } /*GetGlobalMouse*/
  336.  
  337.  
  338.  
  339.  
  340.  
  341.  
  342.  
  343. /*    This is called when an update event is received for a window.
  344.     It calls DrawWindow to draw the contents of an application window.
  345.     As an effeciency measure that does not have to be followed, it
  346.     calls the drawing routine only if the visRgn is non-empty. This
  347.     will handle situations where calculations for drawing or drawing
  348.     itself is very time-consuming. */
  349.  
  350. #pragma segment Main
  351. Boolean gHilite;
  352.  
  353. void DoUpdate(window)
  354.     WindowPtr    window;
  355. {
  356.     if ( IsAppWindow(window) ) {
  357.         BeginUpdate(window);                /* this sets up the visRgn */
  358.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  359.             DrawWindow(window);
  360.         if (gHilite) gHilite = false; else gHilite = true;
  361.         EndUpdate(window);
  362.     }
  363. } /*DoUpdate*/
  364.  
  365.  
  366. /*    This is called when a window is activated or deactivated.
  367.     Since we want to show color changes when activating/deactivating
  368.     we want to have an update in order to display the window in the
  369.     right colors.
  370. */
  371.  
  372. #pragma segment Main
  373. void DoActivate(window, becomingActive)
  374.     WindowPtr    window;
  375.     Boolean        becomingActive;
  376. {
  377.     if ( IsAppWindow(window) ) {
  378.         if ( becomingActive )
  379.             /* do whatever you need to at activation */ 
  380.             InvalRect(&(window->portRect));
  381.         else
  382.             /* do whatever you need to at deactivation */  
  383.             InvalRect(&(window->portRect));
  384.     }
  385. } /*DoActivate*/
  386.  
  387.  
  388. /*    This is called when a mouse-down event occurs in the content of a window.
  389.     Other applications might want to call FindControl, TEClick, etc., to
  390.     further process the click. */
  391.  
  392. #pragma segment Main
  393. void DoContentClick(window)
  394.     WindowPtr    window;
  395. {
  396.     SetLight(window, ! gStopped);
  397. } /*DoContentClick*/
  398.  
  399.  
  400. /* The core shield of tWDEFSample. When an update occurs we draw another window
  401.    using the same technique used by the WDEF.
  402. */
  403.  
  404. #pragma segment Main
  405. void DrawWindow(window)
  406.     WindowPtr    window;
  407. {
  408.     SetPort(window);
  409.  
  410.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  411.     
  412.     FakeWDEF(window, gHilite);
  413.     
  414. } /*DrawWindow*/
  415.  
  416.  
  417.  
  418. #pragma segment Main
  419. void AdjustMenus()
  420. {
  421.     WindowPtr    window;
  422.     MenuHandle    menu;
  423.  
  424.     window = FrontWindow();
  425.  
  426.     menu = GetMHandle(mFile);
  427.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  428.         EnableItem(menu, iClose);
  429.     else
  430.         DisableItem(menu, iClose);    /* but not our traffic light window */
  431.  
  432.     menu = GetMHandle(mEdit);
  433.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  434.         EnableItem(menu, iUndo);
  435.         EnableItem(menu, iCut);
  436.         EnableItem(menu, iCopy);
  437.         EnableItem(menu, iClear);
  438.         EnableItem(menu, iPaste);
  439.     } else {                        /* …but we don’t use it */
  440.         DisableItem(menu, iUndo);
  441.         DisableItem(menu, iCut);
  442.         DisableItem(menu, iCopy);
  443.         DisableItem(menu, iClear);
  444.         DisableItem(menu, iPaste);
  445.     }
  446.  
  447.     menu = GetMHandle(mLight);
  448.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  449.         EnableItem(menu, iStop);
  450.         EnableItem(menu, iGo);
  451.     } else {
  452.         DisableItem(menu, iStop);
  453.         DisableItem(menu, iGo);
  454.     }
  455.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  456.     CheckItem(menu, iGo, ! gStopped);
  457. } /*AdjustMenus*/
  458.  
  459.  
  460. /*    This is called when an item is chosen from the menu bar (after calling
  461.     MenuSelect or MenuKey). It performs the right operation for each command.
  462.     It is good to have both the result of MenuSelect and MenuKey go to
  463.     one routine like this to keep everything organized. */
  464.  
  465. #pragma segment Main
  466. void DoMenuCommand(menuResult)
  467.     long        menuResult;
  468. {
  469.     short        menuID;                /* the resource ID of the selected menu */
  470.     short        menuItem;            /* the item number of the selected menu */
  471.     short        itemHit;
  472.     Str255        daName;
  473.     short        daRefNum;
  474.     Boolean        handledByDA;
  475.  
  476.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  477.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  478.     switch ( menuID ) {
  479.         case mApple:
  480.             switch ( menuItem ) {
  481.                 case iAbout:        /* bring up alert for About */
  482.                     itemHit = Alert(rAboutAlert, nil);
  483.                     break;
  484.                 default:            /* all non-About items in this menu are DAs */
  485.                     /* type Str255 is an array in MPW 3 */
  486.                     GetItem(GetMHandle(mApple), menuItem, daName);
  487.                     daRefNum = OpenDeskAcc(daName);
  488.                     break;
  489.             }
  490.             break;
  491.         case mFile:
  492.             switch ( menuItem ) {
  493.                 case iClose:
  494.                     DoCloseWindow(FrontWindow());
  495.                     break;
  496.                 case iQuit:
  497.                     Terminate();
  498.                     break;
  499.             }
  500.             break;
  501.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  502.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  503.             break;
  504.         case mLight:
  505.             switch ( menuItem ) {
  506.                 case iStop:
  507.                     SetLight(FrontWindow(), true);
  508.                     break;
  509.                 case iGo:
  510.                     SetLight(FrontWindow(), false);
  511.                     break;
  512.             }
  513.             break;
  514.     }
  515.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  516. } /*DoMenuCommand*/
  517.  
  518.  
  519. /* Change the setting of the light. */
  520.  
  521. #pragma segment Main
  522. void SetLight( window, newStopped )
  523.     WindowPtr    window;
  524.     Boolean        newStopped;
  525. {
  526.     if ( newStopped != gStopped ) {
  527.         gStopped = newStopped;
  528.         SetPort(window);
  529.         InvalRect(&window->portRect);
  530.     }
  531. } /*SetLight*/
  532.  
  533.  
  534. /* Close a window. This handles desk accessory and application windows. */
  535.  
  536. /*    1.01 - At this point, if there was a document associated with a
  537.     window, you could do any document saving processing if it is 'dirty'.
  538.     DoCloseWindow would return true if the window actually closed, i.e.,
  539.     the user didn’t cancel from a save dialog. This result is handy when
  540.     the user quits an application, but then cancels the save of a document
  541.     associated with a window. */
  542.  
  543. #pragma segment Main
  544. Boolean DoCloseWindow(window)
  545.     WindowPtr    window;
  546. {
  547.     if ( IsDAWindow(window) )
  548.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  549.     else if ( IsAppWindow(window) )
  550.         CloseWindow(window);
  551.     return true;
  552. } /*DoCloseWindow*/
  553.  
  554.  
  555. /**************************************************************************************
  556. *** 1.01 DoCloseBehind(window) was removed ***
  557.  
  558.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  559.     and not having to worry about updating the windows, but it suffered
  560.     from a fatal flaw. If a desk accessory owned two windows, it would
  561.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  562.     got around to calling DoCloseWindow for that other window that was already
  563.     closed, things would go very poorly. Another option would be to have a
  564.     procedure, GetRearWindow, that would go through the window list and return
  565.     the last window. Instead, we decided to present the standard approach
  566.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  567.     has a potential benefit in that the window whose document needs to be saved
  568.     may be visible since it is the front window, therefore decreasing the
  569.     chance of user confusion. For aesthetic reasons, the windows in the
  570.     application should be checked for updates periodically and have the
  571.     updates serviced.
  572. **************************************************************************************/
  573.  
  574.  
  575. /* Clean up the application and exit. We close all of the windows so that
  576.  they can update their documents, if any. */
  577.  
  578. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  579.     shell, but will return instead. */
  580.  
  581. #pragma segment Main
  582. void Terminate()
  583. {
  584.     WindowPtr    aWindow;
  585.     Boolean        closed;
  586.     
  587.     closed = true;
  588.     do {
  589.         aWindow = FrontWindow();                /* get the current front window */
  590.         if (aWindow != nil)
  591.             closed = DoCloseWindow(aWindow);    /* close this window */    
  592.     }
  593.     while (closed && (aWindow != nil));
  594.     if (closed)
  595.         ExitToShell();                            /* exit if no cancellation */
  596. } /*Terminate*/
  597.  
  598.  
  599. /*    Set up the whole world, including global variables, Toolbox managers,
  600.     and menus. We also create our one application window at this time.
  601.     Since window storage is non-relocateable, how and when to allocate space
  602.     for windows is very important so that heap fragmentation does not occur.
  603.     Because Sample has only one window and it is only disposed when the application
  604.     quits, we will allocate its space here, before anything that might be a locked
  605.     relocatable object gets into the heap. This way, we can force the storage to be
  606.     in the lowest memory available in the heap. Window storage can differ widely
  607.     amongst applications depending on how many windows are created and disposed. */
  608.  
  609. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  610.     this module. If an error is detected, instead of merely doing an ExitToShell,
  611.     which leaves the user without much to go on, we call AlertUser, which puts
  612.     up a simple alert that just says an error occurred and then calls ExitToShell.
  613.     Since there is no other cleanup needed at this point if an error is detected,
  614.     this form of error- handling is acceptable. If more sophisticated error recovery
  615.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  616.  
  617. #pragma segment Initialize
  618. void Initialize()
  619. {
  620.     Handle        menuBar;
  621.     WindowPtr    window;
  622.     long        total, contig;
  623.     EventRecord event;
  624.     short        count;
  625.  
  626.     gInBackground = false;
  627.  
  628.     InitGraf((Ptr) &qd.thePort);
  629.     InitFonts();
  630.     InitWindows();
  631.     InitMenus();
  632.     TEInit();
  633.     InitDialogs(nil);
  634.     InitCursor();
  635.     
  636.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  637.          if you are using it. */
  638.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  639.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  640.         of checking for port availability themselves. */
  641.     
  642.     /*    This next bit of code is necessary to allow the default button of our
  643.         alert be outlined.
  644.         1.02 - Changed to call EventAvail so that we don't lose some important
  645.         events. */
  646.      
  647.     for (count = 1; count <= 3; count++)
  648.         EventAvail(everyEvent, &event);
  649.     
  650.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  651.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  652.         call to SysEnvirons by calling it after initializing AppleTalk. */
  653.      
  654.     SysEnvirons(kSysEnvironsVersion, &gMac);
  655.     
  656.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  657.     
  658.     if (gMac.machineType < 0) AlertUser();
  659.     
  660.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  661.         in TrapAvailable if a tool trap value is out of range. */
  662.         
  663.     gHasWaitNextEvent = TrapAvail(_WaitNextEvent, ToolTrap);
  664.  
  665.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  666.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  667.         MultiFinder we needed. This did not work well because it assumed too much about
  668.         the relationship between what we asked MultiFinder for and what we would actually
  669.         get back, as well as how to measure it. Instead, we will use an alternate
  670.         method comprised of two steps. */
  671.      
  672.     /*    It is better to first check the size of the application heap against a value
  673.         that you have determined is the smallest heap the application can reasonably
  674.         work in. This number should be derived by examining the size of the heap that
  675.         is actually provided by MultiFinder when the minimum size requested is used.
  676.         The derivation of the minimum size requested from MultiFinder is described
  677.         in Sample.h. The check should be made because the preferred size can end up
  678.         being set smaller than the minimum size by the user. This extra check acts to
  679.         insure that your application is starting from a solid memory foundation. */
  680.      
  681.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  682.     
  683.     /*    Next, make sure that enough memory is free for your application to run. It
  684.         is possible for a situation to arise where the heap may have been of required
  685.         size, but a large scrap was loaded which left too little memory. To check for
  686.         this, call PurgeSpace and compare the result with a value that you have determined
  687.         is the minimum amount of free memory your application needs at initialization.
  688.         This number can be derived several different ways. One way that is fairly
  689.         straightforward is to run the application in the minimum size configuration
  690.         as described previously. Call PurgeSpace at initialization and examine the value
  691.         returned. However, you should make sure that this result is not being modified
  692.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  693.         PurgeSpace. Make sure to remove that call before shipping, though. */
  694.     
  695.     /* ZeroScrap(); */
  696.  
  697.     PurgeSpace(&total, &contig);
  698.     if (total < kMinSpace) AlertUser();
  699.  
  700.     /* if color quickdraw is available then we use a color window,
  701.        an old style window is aquired otherwise.
  702.     */
  703.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  704.     if ( window == nil ) AlertUser();
  705.     if (gMac.machineType < envMacII) 
  706.       window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  707.     else
  708.       window = GetNewCWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  709.  
  710.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  711.     if ( menuBar == nil ) AlertUser();
  712.     SetMenuBar(menuBar);                    /* install menus */
  713.     DisposHandle(menuBar);
  714.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  715.     DrawMenuBar();
  716.     
  717.     gStopped = true;
  718.     if ( !GoGetRect(rStopRect, &gStopRect) )
  719.         AlertUser();                        /* the stop light rectangle */
  720.     if ( !GoGetRect(rGoRect, &gGoRect) )
  721.         AlertUser();                        /* the go light rectangle */
  722. } /*Initialize*/
  723.  
  724.  
  725. /*    This utility loads the global rectangles that are used by the window
  726.     drawing routines. It shows how the resource manager can be used to hold
  727.     values in a convenient manner. These values are then easily altered without
  728.     having to re-compile the source code. In this particular case, we know
  729.     that this routine is being called at initialization time. Therefore,
  730.     if a failure occurs here, we will assume that the application is in such
  731.     bad shape that we should just exit. Your error handling may differ, but
  732.     the check should still be made. */
  733.     
  734. #pragma segment Initialize
  735. Boolean GoGetRect(rectID,theRect)
  736.     short    rectID;
  737.     Rect    *theRect;
  738. {
  739.     Handle        resource;
  740.     
  741.     resource = GetResource('RECT', rectID);
  742.     if ( resource != nil ) {
  743.         *theRect = **((Rect**) resource);
  744.         return true;
  745.     }
  746.     else
  747.         return false;
  748. } /* GoGetRect */
  749.  
  750.  
  751. /*    Check to see if a window belongs to the application. If the window pointer
  752.     passed was NIL, then it could not be an application window. WindowKinds
  753.     that are negative belong to the system and windowKinds less than userKind
  754.     are reserved by Apple except for windowKinds equal to dialogKind, which
  755.     mean it is a dialog.
  756.     1.02 - In order to reduce the chance of accidentally treating some window
  757.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  758.     is userKind. If you add different kinds of windows to Sample you'll need
  759.     to change how this all works. */
  760.  
  761. #pragma segment Main
  762. Boolean IsAppWindow(window)
  763.     WindowPtr    window;
  764. {
  765.     short        windowKind;
  766.  
  767.     if ( window == nil )
  768.         return false;
  769.     else {    /* application windows have windowKinds = userKind (8) */
  770.         windowKind = ((WindowPeek) window)->windowKind;
  771.         return (windowKind == userKind);
  772.     }
  773. } /*IsAppWindow*/
  774.  
  775.  
  776. /* Check to see if a window belongs to a desk accessory. */
  777.  
  778. #pragma segment Main
  779. Boolean IsDAWindow(window)
  780.     WindowPtr    window;
  781. {
  782.     if ( window == nil )
  783.         return false;
  784.     else    /* DA windows have negative windowKinds */
  785.         return ((WindowPeek) window)->windowKind < 0;
  786. } /*IsDAWindow*/
  787.  
  788.  
  789. /*    Check to see if a given trap is implemented. This is only used by the
  790.     Initialize routine in this program, so we put it in the Initialize segment.
  791.     The recommended approach to see if a trap is implemented is to see if
  792.     the address of the trap routine is the same as the address of the
  793.     Unimplemented trap. */
  794. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  795.     if a ToolTrap is out of range of a pre-MacII ROM. */
  796.  
  797. #pragma segment Initialize
  798. Boolean TrapAvail(tNumber,tType)
  799.     short        tNumber;
  800.     TrapType    tType;
  801. {
  802.     if ( ( tType == ToolTrap ) &&
  803.         ( gMac.machineType > envMachUnknown ) &&
  804.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  805.         tNumber = tNumber & 0x03FF;
  806.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  807.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  808.     }
  809.  
  810.     return NGetTrapAddress(tNumber, tType) != GetToolTrapAddress(_Unimplemented);
  811. } /*TrapAvail*/
  812.  
  813.  
  814. /*    Display an alert that tells the user an error occurred, then exit the program.
  815.     This routine is used as an ultimate bail-out for serious errors that prohibit
  816.     the continuation of the application. Errors that do not require the termination
  817.     of the application should be handled in a different manner. Error checking and
  818.     reporting has a place even in the simplest application. The error number is used
  819.     to index an 'STR#' resource so that a relevant message can be displayed. */
  820.  
  821. #pragma segment Main
  822. void AlertUser()
  823. {
  824.     short        itemHit;
  825.  
  826.     SetCursor(&qd.arrow);
  827.     itemHit = Alert(rUserAlert, nil);
  828.     ExitToShell();
  829. } /* AlertUser */